package com.likuicat.cataiagentbackend.app;

import com.likuicat.cataiagentbackend.advisor.MyLoggerAdvisor;
import com.likuicat.cataiagentbackend.advisor.ReReadingAdvisor;
import com.likuicat.cataiagentbackend.chatmemory.FileBasedChatMemory;
import com.likuicat.cataiagentbackend.constant.FileConstant;
import com.likuicat.cataiagentbackend.rag.LoveAppRagCustomAdvisorFactory;
import com.likuicat.cataiagentbackend.rag.LoveAppVectorStoreConfig;
import com.likuicat.cataiagentbackend.rag.QueryRewriter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.client.advisor.QuestionAnswerAdvisor;
import org.springframework.ai.chat.client.advisor.SimpleLoggerAdvisor;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.tool.ToolCallback;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.stereotype.Component;

import java.util.List;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
@Slf4j
public class LoveApp {

    //本地RAG知识库
    @Resource
    private VectorStore loveAppVectorStore;

    //云端RAG知识库
    @Resource
    private Advisor loveAppRagCloudAdvisor;

    //pgvector向量存储RAG知识库
    @Resource
    private VectorStore pgVectorVectorStore;

    @Resource
    private QueryRewriter queryRewriter;



    private final ChatClient chatClient;

    private final  static String SYSTEM_PROMPT =
            "扮演深耕恋爱心理领域的专家。开场向用户表明身份，告知用户可倾诉恋爱难题。"+
            "围绕单身、恋爱、已婚三种状态提问：单身状态询问社交圈拓展及追求心仪对象的困扰；" +
            "恋爱状态询问沟通、习惯差异引发的矛盾；已婚状态询问家庭责任与亲属关系处理的问题。"+
            "引导用户详述事情经过、对方反应及自身想法，以便给出专属解决方案。";

    public LoveApp(ChatModel dashscopeChatModel) {
        String filepath = FileConstant.FILE_SAVE_DIR + "/chat-memory";
        //初始化基于文件的对话记忆
        ChatMemory chatMemory = new FileBasedChatMemory(filepath);

        //初始化基于内存的对话记忆
//        ChatMemory chatMemory = new InMemoryChatMemory();

        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                .defaultAdvisors(
                        new MessageChatMemoryAdvisor(chatMemory),
                        new MyLoggerAdvisor()  //记录日志
//                        ,new ReReadingAdvisor()  //再次加强prompt
                )
                .build();
    }

    /**
     * 多轮对话
     * @param message
     * @param chatId
     * @return
     */
    public String doChat(String message,String chatId){
        ChatResponse chatResponse = chatClient.prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String text = chatResponse.getResult().getOutput().getText();
        log.info("回复 ： {}" , text);
        return text;
    }

    //jdk14特性 快速生成class类
    record  LoveReport(String text, List<String> list){

    }

    /**
     * 多轮对话
     * 转换为class类的格式输出
     * @param message
     * @param chatId
     * @return
     */
    public LoveReport doChatWithReport(String message,String chatId){
        LoveReport report = chatClient.prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成恋爱结果，标题为{用户名}的恋爱报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(LoveReport.class);
        log.info("报告 ： {}" , report);
        return report;
    }



    /**
     * 多轮对话
     * RAG知识库问答
     * @param message
     * @param chatId
     * @return
     */
    public String doChatWithRag(String message,String chatId){
        //对用户查询语句重写
        String rewrite = queryRewriter.doQueryRewrite(message);

        ChatResponse chatResponse = chatClient.prompt()
                .user(rewrite)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10)) //设置对话记忆
                //添加本地RAG知识库问答
//                .advisors(new QuestionAnswerAdvisor(loveAppVectorStore))
                //添加云端RAG知识库问答
//                .advisors(loveAppRagCloudAdvisor)
                //应用RAG检索增强服务（基于PgVector向量存储）
//                .advisors(new QuestionAnswerAdvisor(pgVectorVectorStore))
                .advisors(LoveAppRagCustomAdvisorFactory
                        .createLoveAppRagCustomAdvisor(
                                loveAppVectorStore,"单身"
                        ))
                .call()
                .chatResponse();
        String text = chatResponse.getResult().getOutput().getText();
        log.info("回复 ： {}" , text);
        return text;
    }

    @Resource
    private ToolCallback[] allTools;

    public String doChatWithTools(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                // 开启日志，便于观察效果
                .advisors(new MyLoggerAdvisor())
                .tools(allTools)
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }


}
